package Java练习.字符串练习;

import java.util.Scanner;

public class 金额转换 {
    public static void main(String[] args) {
        Scanner sc=new Scanner(System.in);
        String str= null;
        while (true) {
            System.out.print("请输入要转换的数字:");
            str = sc.next();
            if (conver_num(str)>0&&conver_num(str)<=10000000){
                break;
            }else {
                System.out.println("输入不合法!请重新输入!");
            }
        }
        //把数字转换为中文
        String[] new_str=convert(str);
        int count=str.length();
        //在数字前面加零
        String bin="";
        int a=0;
        for (int i = 0; i < 7; i++) {

            if(i<7-count){
                bin+="零";
            }else {
                bin+=new_str[a];
                a++;
            }
        }
        //插入单位
        String new_bin="";
        String[] danwei={"佰","拾","万","仟","佰","拾","元",};
        for (int i = 0; i < bin.length(); i++) {
           new_bin+=bin.charAt(i)+danwei[i];
        }
        System.out.println(new_bin);
    }
    //定义一个方法实现中文和数字转换
    public static String[] convert(String str){
        String[] ch_num={"零","壹","贰","叁","肆","伍","陆","柒","捌","玖"};
        //定义一个数组存储中文数字
        String[] arr=new String[str.length()];
        for (int i = 0; i < str.length(); i++) {
            //得到对应索引的字符
            char s=str.charAt(i);
            //把获取到的对应字符转化为相应的数字
            int num=char_convert_int(s);
            //转化为中文并存储
            arr[i]=ch_num[num];
        }
        return arr;
    }
    //定义一个把字符数字转化为数字的方法
    public static int char_convert_int(char ch){
        switch (ch){
            case '0'-> {return 0;}
            case '1'-> {return 1;}
            case '2'-> {return 2;}
            case '3'-> {return 3;}
            case '4'-> {return 4;}
            case '5'-> {return 5;}
            case '6'-> {return 6;}
            case '7'-> {return 7;}
            case '8'-> {return 8;}
            case '9'-> {return 9;}
        }
        return -1;
    }
    //定义一个方法把字符串数字转化为数字
    private static int conver_num(String str){
        int sum=0;
        for (int i = 0; i < str.length(); i++) {
            char ch=str.charAt(i);
            int num=char_convert_int(ch);
            sum=sum*10+num;
        }
        return sum;
    }
}
